import { createRouter, createWebHashHistory } from "vue-router";
import { arrTreeToArr } from '@/utils/utils'
import { getSysMenusApi } from '@/api/api'
import store from '@/store'

const routes = [
  {
    path: '/', // 登录
    name: 'login',
    component: () => import("@/views/login.vue")
  }, {
    path: '/register', // 注册
    name: 'register',
    component: () => import("@/views/register.vue")
  }, {
    path: '/index',
    name: 'index',
    component: () => import('@/views/zcytFrame/index.vue'),
    children: []
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})

router.beforeEach(async (to, from, next) => {
  if(!to.name && !from.name) { // 页面刷新时候执行
    // 获取当前用户菜单权限数据
    await getSysMenusApi().then(res => {
      if(res.code === '200') {
        window.sessionStorage.setItem('menuCache', JSON.stringify(res.data))
        const loadComp = import.meta.glob('@/views/**/*.vue')
        const menus = arrTreeToArr(res.data, 'childList') // 将树形对象数组转为一维扁平对象数组
        menus.forEach(item => {
          if(item.router && item.url) {
            // 将用户具有的菜单路由添加进路由
            router.addRoute('index', {
              path: `/${item.router}`,
              name: item.router,
              component: loadComp[`/src/views/${item.url}.vue`]
            })
          }
        })
      }
    })
    store.commit('include', [to.path.slice(1)]) // 将页面缓存
    next(to.path)
  } else {
    next()
  }
})

export default router